package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    public void save(Employee entity) {

        //初始化密码
        entity.setPassword(new Md5Hash("1").toString());
        //设置初始化状态
        entity.setState(Employee.STATE_NORMAL);
        //设置入职时间
        //entity.setHiredate(new Date());

        mapper.insert(entity);
        List<Role> roles = entity.getRoles();
        if (roles != null) {
            for (Role role : roles) {
                mapper.saveEmployeeRoleRelation(entity.getId(), role.getId());
            }
        }
    }

    public void update(Employee entity) {
        mapper.updateByPrimaryKey(entity);
        mapper.deleteEmployeeRoleRelation(entity.getId());
        List<Role> roles = entity.getRoles();
        if (roles != null) {
            for (Role role : roles) {
                mapper.saveEmployeeRoleRelation(entity.getId(), role.getId());
            }
        }
    }

    public void delete(long id) {
        mapper.deleteEmployeeRoleRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    public Employee get(long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return mapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Employee> list = mapper.queryForList(qo);
        return new PageResult(total, list);
    }

    public Employee checkName(String username) {

        return mapper.checkName(username);
    }

    public void changeState(Long id) {
        mapper.changeState(id);
    }

    public void changeByPassword(Employee entity) {
        mapper.updateByPassword(entity);
    }

}
